#!/usr/bin/perl -wT
use CGI qw(:standard);
use lib '.';
use users;
use strict;

my $user = param('username');
my $pass = param('password');
my $username = "";


my ($cuser,$epass,$email,$level,$active,$gname) = checkuser($user);
if ($cuser eq $user)
{
    my $salt = substr($epass, 0, 2);
    if ($epass ne crypt($pass, $salt) ) {
		&dienice("You Entered the wrong password - please try again");
    }
    $username = $user;
} else {
    &dienice("Username <b>$user</b> does not exist.");
}
if ($active==0)
{
	&dienice ("An Administrator has not activated your account yet - Please try later");
}

my $cookie_id = &random_id;
my $cookie = cookie(-name=>'cid', -value=>$cookie_id, -expires=>'+7d');

save_cookie($user,$cookie_id) or &dienice("cannot write cookie data to server");

if (param('page')) {
   my $url = param('page');
   # CGI.pm's redirect function can accept all of the same parameters
   # as the header function, so we can set a cookie and issue a redirect
   # at the same time.
   print redirect(-location=>"$url", -cookie=>$cookie);
} else { 
   # no page was specified, so print a "you have logged in" message.
   # On a production site, you may want to change this to print
   # a redirect to your home page...
  # print header(-cookie=>$cookie);
   print redirect(-location=>"menu.cgi", -cookie=>$cookie);
#   print start_html("Logged In");
#   print qq(<h2>Welcome</h2>\nYou're logged in as <b>$username</b>!<br>\n);
#   print qq(<a href="menu.cgi">go to main menu</a><br>\n);
#   print qq(<a href="logout.cgi">log out</a><br>\n);
#   print end_html;
}

sub random_id {
    # This routine generates a 32-character random string
    # out of letters and numbers.
    my $rid = "";
    my $alphas = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    my @alphary = split(//, $alphas);
    foreach my $i (1..32) {
       my $letter = $alphary[int(rand(@alphary))];
       $rid .= $letter;
    }
    return $rid;
}
